class Ten:
  def __get__(self,obj,objtype=None):
    return 10


class A():
  x = 5
  y = Ten()

a = A()
print(a)
print(a.x)
print(a.y)
# 请注意，值 10 既不存储在类字典中也不存储在实例字典中。相反，值 10 是在调用时才取到的。

# 这个简单的例子展示了一个描述器是如何工作的，但它不是很有用。在查找常量时，用常规属性查找会更好。

# 在下一节中，我们将创建更有用的东西，即动态查找。


print(50 * '=')
import os

class DirectorySize:
    def __get__(self, obj, objtype=None):
        print('__get__')
        print(self.__dict__)
        print(obj.__dict__)
        # print(objtype.size)
        return len(os.listdir(obj.dirname))
class Directory:
    size = DirectorySize()
    def __init__(self, dirname):
        self.dirname = dirname
s = Directory('magics/songs')

# print(s)
print(s.size)

import logging

logging.basicConfig(level=logging.INFO)

class LoggedAgeAccess:
    def __get__(self, obj, objtype=None):
        value = obj._age
        logging.info('Accessing %r giving %r', 'age', value)
        return value

    def __set__(self, obj, value):
        logging.info('Updating %r to %r', 'age', value)
        obj._age = value

class Person:

    age = LoggedAgeAccess()             # Descriptor instance

    def __init__(self, name, age):
        self.name = name                # Regular instance attribute
        self.age = age                  # Calls __set__()

    def birthday(self):
        self.age += 1                   # Calls both __get__() and __set__()

mary = Person('Mary M', 30)
